import Ember from 'ember';

export default Ember.Route.extend({
	notify: Ember.inject.service('notify'),
	websockets: Ember.inject.service(),
	socketRef: null,
	allMessages:[],
	beforeModel() {
		console.log(window.location.host);
		const socket = this.get('websockets').socketFor(`ws://${window.location.host}/websocket?username=hah`);
		socket.on('open', this.myOpenHandler, this);
		socket.on('message', this.myMessageHandler, this);
		socket.on('close', this.myCloseHandler, this);

		this.set('socketRef', socket);
	},

	myOpenHandler(event) {
		console.log(`On open event has been called: ${event}`);
	},

	myMessageHandler(event) {
		console.log(`Message: ${event.data}`);
		let allMessages = this.get("allMessages");
		allMessages.push(event.data);
		let startIndex = allMessages.length - 1000;
		if (startIndex < 0) {
			startIndex = 0;
		}
		this.controller.set("messages", allMessages.slice(startIndex));
	},

	myCloseHandler(event) {
		console.log(`On close event has been called: ${event}`);
	},

	actions: {
		sendButtonPressed(message) {
			if (!message) {
				this.get('notify').warning('信息不能为空!');
				return;
			}
			console.log(message);
			const socket = this.get('socketRef');
			socket.send(message);
		}
	}
});
